<?php

namespace App\Engine;


use Carbon\Carbon;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Facades\Cache;
use Ramsey\Uuid\Uuid;
use App\Engine\phpqrcode\QRcode;
use function app\Utils\go;
use function EasyWeChat\Kernel\Support\str_random;
use Illuminate\Support\Facades\Log;

require_once 'phpqrcode/phpqrcode.php';

class BaseCommon
{
    function curl_get($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
            )
        );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }



    function curl_post($url, array $params = array())
    {
        $data_string = json_encode($params);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }

    function curl_post_tui($url, array $params = array())
    {
        $data_string = json_encode($params);



        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json;charset=utf-8',
                'token:'.Cache::get('tui_token')
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }

    public function create_qrcode()
    {
        $phrase=new PhraseBuilder();
        $code=$phrase->build(4);
        $builder=new CaptchaBuilder($code,$phrase);
        $builder->setBackgroundColor(34,0,45);
        $builder->setMaxAngle(5 );
        $builder->setMaxBehindLines(10);
        $builder->setMaxFrontLines(10);
        $builder->setTextColor(230,81,175);
        $builder->build(150,40);
        $phrase=$builder->getPhrase();
        $client_id=Uuid::uuid1()->toString();
        Cache::put($client_id,$phrase,Carbon::now()->addMinute(2));
        $data=[
            'client'=>$client_id,
            'captcha'=>$builder->inline()
        ];
        return $data;
    }

    /**
     * 订单编号生成
     */
    public function create_order_num($type="C")
    {
        $orderSn =
           $type. strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }

    /**生成订单二维码
     * @param $code
     */
    public function createCode($data)
    {
        $name=md5(rand(1000,100000).time());
        $send_path="/uploads/code/{$name}.png";
        $qr = base_path()."/public".$send_path;

        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 10;//生成图片大小
        $data=base64_encode($data);
        \QRcode::png($data, $qr, $errorCorrectionLevel, $matrixPointSize, 2);

        return [
            'path'=>$send_path
        ];
    }

    /**
     * 跳转app二维码生成
     * **/
    public function createAppCode($code_value,$name="")
    {
        if($name==""){
            $name=md5(str_random(20).time());
        }
        $send_path="/uploads/code/{$name}.png";
        $qr = base_path()."/public".$send_path;
        $path=$qr;
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 10;//生成图片大小
        $data=SysConfig::getValue('api_url')."/open/h5?";
        //$data="http://192.168.10.112:8081/open/h5?";
        foreach ($code_value as $key=>$val){
            $data.=$key."=".$val."&";
        }
        $data=substr($data,0,strlen($data)-1);
         \QRcode::png($data, $qr, $errorCorrectionLevel, $matrixPointSize, 2);
          return [
            'path'=>$send_path
        ];

    }

    public function ObjToArr($obj)
    {
        $arr=array();
        foreach ($obj as $key=>$value){
            $arr[$key]=$value;
        }
        return $arr;
    }


    public function createQrlib()
    {
        $content="张三\n";
        $res=\QRcode::png($content);
        return $res;
    }

    public function compressedImage($imgsrc, $imgdst) {
        list($width, $height, $type) = getimagesize($imgsrc);
        $new_width = $width>800?800:$width;//图片宽度的限制
        $new_height =$height>800?ceil($height*800/$width):$height;//自适应匹配图片高度
        switch ($type) {
            case 1:
                $giftype = $this->check_gifcartoon($imgsrc);
                if ($giftype) {
                    header('Content-Type:image/gif');
                    $image_wp = imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
                    imagejpeg($image_wp, $imgdst, 90);
                    imagedestroy($image_wp);
                    imagedestroy($image);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 90);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 90);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;
        }
    }

    private function check_gifcartoon($image_file){
        $fp = fopen($image_file,'rb');
        $image_head = fread($fp,1024);
        fclose($fp);
        return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;

    }

    function getImgs($content,$order='ALL')
    {
        $pattern ="/<img .*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$content,$match);
        if(isset($match[1])&&!empty($match[1])){
            if($order==='ALL'){
                return $match[1];
            }
            if(is_numeric($order)&& isset($match[1][$order])){
                return $match[1][$order];
            }
        }
        return'';
    }




}
